package com.example.order.mq;

import com.alibaba.fastjson.JSON;
import com.example.order.IUserService;
import com.example.order.constant.ShopCode;
import com.example.order.entity.MQEntity;
import com.example.order.entity.TradeOrder;
import com.example.order.entity.TradeUserMoneyLog;
import com.example.order.mapper.TradeOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;

@Slf4j
@Component
@RocketMQMessageListener(topic = "${mq.order.topic}",consumerGroup = "${mq.order.consumer.group.name}",messageModel = MessageModel.BROADCASTING)
public class CancelMQListener implements RocketMQListener<MessageExt> {

    @Value("${mq.order.topic}")
    private String groupName;

    @Resource
    private TradeOrderMapper orderMapper;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
        //1.解析消息
            String body = new String(messageExt.getBody(),"UTF-8");
            MQEntity mqEntity = JSON.parseObject(body,MQEntity.class);
            log.info("接收到消息");
//            2.查询订单
            TradeOrder order = orderMapper.selectByPrimaryKey(mqEntity.getOrderId());
//            3.更新订单状态为取消
            order.setOrderStatus(ShopCode.SHOP_ORDER_MESSAGE_STATUS_CANCEL.getCode());
            orderMapper.updateByPrimaryKey(order);
            log.info("订单设置为取消");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("余额回退失败");
        }
    }
}
